package com.zqf.shiro.config;

import com.zqf.shiro.filter.JwtToken;
import com.zqf.shiro.jwt.JwtAudience;
import com.zqf.shiro.pojo.LoginUser;
import com.zqf.shiro.pojo.User;
import com.zqf.shiro.service.UserService;
import com.zqf.shiro.utils.JwtHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Set;

/**
 * @Author zqf
 * @Date 2022/12/15 16:31
 * @Description: 授权认证
 */
@Slf4j
@Service
public class MyRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    private final JwtAudience jwtAudience;

    @Autowired
    public MyRealm(JwtAudience jwtAudience) {
        this.jwtAudience = jwtAudience;
    }

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        LoginUser loginUser = JwtHelper.verifySignedAndGetUser(principals.toString(), jwtAudience.getBase64Secret());
        if (Objects.isNull(loginUser)) {
            throw new UnauthorizedException("授权失败");
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(loginUser.getRoles());
        //simpleAuthorizationInfo.addStringPermissions(loginUser.getPerms());
        log.debug("loginUser:{}", loginUser);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        LoginUser loginUser = JwtHelper.verifySignedAndGetUser(token, jwtAudience.getBase64Secret());
        if (loginUser == null) {
            throw new AuthenticationException("认证失败");
        }
        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }
}
